package com.cy.store.controller;

import com.cy.store.service.ex.*;
import com.cy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

public class BaseController {
    public static final int OK = 200;

    @ExceptionHandler(ServiceExeption.class)
    public JsonResult<Void> handlerException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);

        if(e instanceof UsernameDulplicatedExeption){
            result.setState(4000);
            result.setMessage("用户名被占用");
        }else if(e instanceof UsernameNotFoundException){
            result.setState(5001);
            result.setMessage("用户数据不存在异常");
        }else if(e instanceof PasswordNotMatchException){
            result.setState(5002);
            result.setMessage("用户密码错误异常");
        }
        else if(e instanceof InsertExeption){
            result.setState(5000);
            result.setMessage("插入数据时产生未知的异常");
        }
        return result;
    }

    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
